<?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Request;
use think\Db;
const ERRNO = [
    'OK'         => 200,
    'TOKENOUT'   => 4101, //access_token过期
    'REQUESTERR' => 4102, //请求错误
    'TOKENERR'   => 4103,//token格式错误
    'LoginNeed'  => 4105,//需要登录
    'OTHERERR'   => 4104,
    'REFRESHOUT' => 4107,//refresh_token过期
    'PARAMERR'   => 4106,
    'USERCANCEL' => 4108,
    'SIGNERR'    => 4109,
    'ROLEERR'    => 4201,
    'AIRPORTERR' => 4202, //首页读取不到airport信息
    'POSTSERR'   => 4203,
    'QRCODEERR'  => 4204,  //扫码登录过期
    'RESULTEMPTY'=> 4205,
    'IOERR'      => '4302',
    'SERVERERR'  =>  500,
    'UNKOWNERR'  => '4501',
];

if (!function_exists('getToken')) {
    /**
     *
     * @param $userInfo
     * @param $type  1:access_token  2:refresh_token 3:qrcode token
     */
    function getToken($userInfo,$type=1){
        if($type!=3){
            $data=[  // 自定义信息，不要定义敏感信息
                'id' => $userInfo['id'],
                //'username' => $userInfo['username'],
                'type'=>$userInfo['type'],
                'country'=>$userInfo['country']
            ];
        }
        $expire_time=0;
        $key = config('jwt.access_key');  // key
        $time = time();  // 当前时间
//        $expire_time=($type==1)?config('jwt.access_token_expire'):config('jwt.refresh_token_expire');
        switch ($type){
            case 1:
                $expire_time= config('jwt.access_token_expire');
                break;
            case 2:
                $expire_time= config('jwt.refresh_token_expire');
                break;
            case 3:
                $expire_time=60;
                $data['id']=$userInfo['user_id'];
                break;
            default:
                break;
        }
        $token = [
            'iat' => $time,  // 签发时间
            'iss' => 'envee_admin',
            'nbf' => $time ,  // (Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time + $expire_time,  // 过期时间,这里设置2个小时
            'jti' => md5(uniqid('JWT').time()),//该Token唯一标识
            'data' => $data
        ];
        return JWT::encode($token, $key,'HS256');  // 输出Token
    }
}

if (!function_exists('verification')) {
    /**
     * @param $token
     * @param int $type 1:access_token  2:refresh_token 3:qrcode token
     * @return array
     * @throws Exception
     */
    function verification($token,$type=1)
    {
        $key = config('jwt.access_key');  // key要和签发的时候一样
        try {
            JWT::$leeway = 60;  // 当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token,new Key($key,"HS256"));  // HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            return $arr;
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  // 签名不正确
            throw new \Firebase\JWT\SignatureInvalidException('签名不正确', 4103);
        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            echo $e->getMessage();
        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
            if($type==1){
                throw new \Firebase\JWT\ExpiredException('access token expiration', 4101);
            }elseif($type==2){
                throw new \Firebase\JWT\ExpiredException('User information has expired and needs to be logged in again', 4107);
            }else{
                throw new \Firebase\JWT\ExpiredException('Scan code login expired', ERRNO['QRCODEERR']);
            }
        }catch(Exception $e) {  // 其他错误
            throw new Exception($e->getMessage());
        }
    }
}
if (!function_exists('salt')) {
    function salt(){
        $salt = '';
        for ($i = 0; $i < 6; $i++) {
            $salt .= chr(mt_rand(33, 126));
        }
        return $salt;
    }
}

if (!function_exists('format_phone')) {
    function format_phone($phone){
        //18884852074
        //11-4=7/2=3
        $length=strlen($phone);
        $begin=floor(($length-4)/2);
        return substr_replace($phone,'****',$begin,4);


    }
}

if (!function_exists('getFirstCharter')) {
    function getFirstCharter($str)
    {
        if(empty($str)){return '';}
        $fchar=ord($str{0});
        if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
        try{
            $s1=iconv('UTF-8','gb2312',$str);
            $s2=iconv('gb2312','UTF-8',$s1);
        }catch (\Exception $e){
            $s1=iconv('UTF-8','GBK',$str);
            $s2=iconv('GBK','UTF-8',$s1);
        }
//        $s1=iconv('UTF-8','gb2312',$str);
//        $s2=iconv('gb2312','UTF-8',$s1);

        $s=$s2==$str?$s1:$str;
        $asc=ord($s{0})*256+ord($s{1})-65536;
        if($asc>=-20319&&$asc<=-20284) return 'A';
        if($asc>=-20283&&$asc<=-19776) return 'B';
        if($asc>=-19775&&$asc<=-19219) return 'C';
        if($asc>=-19218&&$asc<=-18711) return 'D';
        if($asc>=-18710&&$asc<=-18527) return 'E';
        if($asc>=-18526&&$asc<=-18240) return 'F';
        if($asc>=-18239&&$asc<=-17923) return 'G';
        if($asc>=-17922&&$asc<=-17418) return 'H';
        if($asc>=-17417&&$asc<=-16475) return 'J';
        if($asc>=-16474&&$asc<=-16213) return 'K';
        if($asc>=-16212&&$asc<=-15641) return 'L';
        if($asc>=-15640&&$asc<=-15166) return 'M';
        if($asc>=-15165&&$asc<=-14923) return 'N';
        if($asc>=-14922&&$asc<=-14915) return 'O';
        if($asc>=-14914&&$asc<=-14631) return 'P';
        if($asc>=-14630&&$asc<=-14150) return 'Q';
        if($asc>=-14149&&$asc<=-14091) return 'R';
        if($asc>=-14090&&$asc<=-13319) return 'S';
        if($asc>=-13318&&$asc<=-12839) return 'T';
        if($asc>=-12838&&$asc<=-12557) return 'W';
        if($asc>=-12556&&$asc<=-11848) return 'X';
        if($asc>=-11847&&$asc<=-11056) return 'Y';
        if($asc>=-11055&&$asc<=-10247) return 'Z';
        return null;
    }
}

/*
 * $contact 一个数组
 */
if (!function_exists('doing')) {
    function doing($data){
        $sortData=[];
        $data = array_map(function ($item) {
            return array_merge($item, [
                'initials' => getFirstCharter($item['name']),
            ]);
        }, $data);
//        $res=[];
//        foreach ($data as $key => $value) {
//            $sortData[$value['initials']][] = $value;
//        }
//        $i=0;
//        foreach ($sortData as $k=>$v){
//            $res[$i]['title']=$k;
//            $res[$i]['data']=$v;
////            $res[]=$v;
//            $i++;
//        }
//        ksort($sortData);
        return $data;
    }
}

if (!function_exists('encrypt')) {
    function encrypt($arr)
    {
        $arr['appName'] = config('app.keyword');
        $arr['timestamp'] = time();
        $keys = array_keys($arr);
        sort($keys);
        $newArr = [];
        foreach ($keys as $key) {
            $newArr[$key] = $arr[$key];
        }
        $query = base64_encode(urlencode(json_encode($newArr)));
        $sign = '';
        $confusionStr = getRandomStr(32);
        for ($i = 0; $i < 32; $i++) {
            $sign .= (isset($query[$i]) ? $query[$i] : '') . $confusionStr[$i];
        }
        $sign = $sign . substr($query, 32, strlen($query) - 32);
        return $sign;
    }
}
if (!function_exists('decrypt')) {
    function decrypt($sign)
    {
        if (strlen($sign) < 64) {
            return false;
        }
        $query = '';
        for ($i = 0; $i < 64; $i++) {
            if ($i % 2 == 0) {
                $query .= $sign[$i];
            }
        }

        $query = $query . substr($sign, 64, strlen($sign) - 32);
        $arr = json_decode(urldecode(base64_decode($query)), true);
        if (isset($arr['appName']) && $arr['appName'] != config('app.keyword')) {
            return false;
        }

        if (!isset($arr['timestamp']) || (abs(time() - $arr['timestamp']) > 1800)) {
            return false;
        }
        return $arr;
    }

}

if (!function_exists('getRandomStr')) {
    function getRandomStr($len)
    {
        $confusion = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ,`.~!@#$%^&*()/.,;{}[]';

        $confusionLen = strlen($confusion);
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $rand = rand(0, $confusionLen - 1);
            $str .= ($confusion)[$rand];
        }
        return $str;
    }
}


if (!function_exists('handleTimeZone')) {
    function handleTimeZone($timezone,$info){
        $week=json_decode($info['week'],true);
        $start_time=$info['start_time'];
        $end_time=$info['end_time'];

        $merchant_time=time()+($timezone*3600);
        $merchant_week=date('N',$merchant_time);
        $merchant_start_time=date('H:i:s',$merchant_time);
        $merchant_end_time=date('H:i:s',$merchant_time);
        //周几不在经营范围内
        if(!in_array($merchant_week,$week)) return 0;
        if($start_time>$merchant_start_time) return 0;
        if($end_time<=$merchant_end_time) return 0;
        return 1;
    }
}
if (!function_exists('is_login')) {
    function is_login(){
        $access_token=Request::header('token');
        if(empty($access_token)){
            return false;
        }

        $data=verification($access_token);
        $userInfo=$data['data'];
        return $userInfo;
    }
}

if (!function_exists('handleOpenTime')) {
    function handleOpenTime($week,$start_time,$end_time,$country)
    {
        $flag=0;
        $week=json_decode($week,true);
        $cur_week=$week;
        $diff_time=Db::table(config('database.prefix').'area')->where('id',$country)->value('timezone');
        $start_time_arr=explode(':',$start_time);
        $end_time_arr=explode(':',$end_time);
        $start_time=$start_time_arr[0]-$diff_time;
        $end_time=$end_time_arr[0]-$diff_time;
        if($start_time<0 || $start_time>24){
            $cur_week=[];
            $flag=1;
            foreach ($week as $val){
                if($start_time<0){
                    $cur_week[]=$val-1==0?7:$val-1;
                }else{
                    $cur_week[]=$val+1==8?1:$val+1;
                }
            }
            $start_time=$start_time<0?24+$start_time:$start_time-24;
        }
        if($end_time<0 || $end_time>24){
            $cur_week=[];
            $end_time=$end_time<0?24+$end_time:$end_time-24;
            if(!$flag){
                foreach ($week as $val){
                    if($end_time<0){
                        $cur_week[]=$val-1==0?7:$val-1;
                    }else{
                        $cur_week[]=$val+1==8?1:$val+1;
                    }
                }
            }
        }

        sort($cur_week);
        $res['week']=json_encode($cur_week);
        $res['start_time']=$start_time.':'.$start_time_arr[1];
        $res['end_time']=$end_time.':'.$end_time_arr[1];
        return $res;
    }
}

/**
 * 定位所在时区转换为UTC时区
 */
if (!function_exists('localTobase')) {
    function localToBase($time,$country){
        $diff_time=Db::table(config('database.prefix').'area')->where('id',$country)->value('timezone');
        $base_time=strtotime($time)-($diff_time*3600);
        return date('Y-m-d H:i:s',$base_time);
    }
}

/**
 * 处理帖子发布时间
 */
if (!function_exists('openTime')) {
    function openTime($time,$timeZone)
    {
        $diff_time=time()-strtotime($time);
        switch ($diff_time){
            case $diff_time<60:
                return 'one minute ago';
            case $diff_time<3600:
                //n<60min
                return floor($diff_time/60).' minute(s) ago';
                break;
            case $diff_time<=60*60*24:
                return floor($diff_time/3600).' hour(s) ago';
                break;
            case $diff_time<=60*60*24*7:
                return floor($diff_time/(3600*24)).' day(s) ago';
                break;
            default:
                $time=strtotime($time)+$timeZone*3600;
                return date('d/m,Y',$time);

        }
    }
}

if (!function_exists('getMerchantAvatar')) {
    function getMerchantAvatar($avatar)
    {
        if($avatar){
            return get_file_path($avatar);
        }else{
            return get_file_path(config('data.merchant_avatar_default'));
        }
    }
}

//if (!function_exists('getUserAvatar')) {
//    function getUserAvatar($avatar)
//    {
//        if($avatar){
//            return get_file_path($avatar);
//        }else{
//            return get_file_path(config('data.user_avatar_default'));
//        }
//    }
//}
if (!function_exists('getVideoCover')) {
    //获得视频文件的缩略图
    function getVideoCover($file,$time,$name) {
        if(empty($time))$time = '1';//默认截取第一秒第一帧
        $strlen = strlen($file);
        // $videoCover = substr($file,0,$strlen-4);
        // $videoCoverName = $videoCover.'.jpg';//缩略图命名
        //exec("ffmpeg -i ".$file." -y -f mjpeg -ss ".$time." -t 0.001 -s 320x240 ".$name."",$out,$status);
        $str = "ffmpeg -i ".$file." -y -f mjpeg -ss ".$time." -s 160x140 ".$name.' >> log_file.log 2>&1 &';
        return system($str);
    }
}

if (!function_exists('getTime')) {
    //获得视频文件的总长度时间和创建时间
    function getTime($file){
        $vtime = exec("ffmpeg -i ".$file." 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");//总长度
        $vtime=substr($vtime,0,strpos($vtime,'.'));
        return $vtime;
    }
}

if (!function_exists('merchantStatus')) {
    function merchantStatus($country_timezone,$info){
        //1.open now的商户，2.未配置营业时间的商户，3.close now的商户，4.Pause状态商户
        if($info['is_pause']){
            $open_status=4;
        }else{
            if(empty($info['week'])){
                $open_status=2;//未配置
            }else{
                $flag=handleTimeZone($country_timezone,$info);
                if($flag){
                    $open_status=1;
                }else{
                    $open_status=3;
                }
            }
        }
        return $open_status;
    }
}

if (!function_exists('handleEventTime')) {
    function handleEventTime($start_time,$end_time){
        $date=date('M.jS',strtotime($start_time)).'-'.date('M.jS',strtotime($end_time));
        $time=date('H:i',strtotime($start_time)).'-'.date('H:i',strtotime($end_time));
        $str=$date.': Daily '.$time;
        return $str;
    }
}


